package cloudContact.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.mybeans.factory.RollbackException;
import org.scribe.model.Token;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;

import cloudContact.GoogleConstant;
import cloudContact.MyDAOException;
import cloudContact.SecurityManager;
import cloudContact.DAO.User;
import cloudContact.DAO.UserDAO;


/**
 * Servlet implementation class GoogleOAuthCallback
 */
@WebServlet("/GoogleOAuthCallback")
public class GoogleOAuthCallback extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public GoogleOAuthCallback() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 * @see http://code.google.com/apis/gdata/docs/auth/oauth.html#Examples
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		System.out.println("Start GoogleOAuthCallback...");

		// Security check
		try {
			if (!SecurityManager.CheckAuthorization(request)) {
				System.out.println("Error: User is not authorized.");
				return;
			}
		} catch (RollbackException e1) {
			e1.printStackTrace();
		} catch (MyDAOException e1) {
			e1.printStackTrace();
		}
		
		HttpSession session = request.getSession();
		Token requestToken = null;
		try {
			User user = UserDAO.getInstance().lookup(session.getAttribute("userId").toString());
			requestToken = new Token(user.getGMailAccessToken(),user.getGMailAuthSecrete());
			
			OAuthService service = GoogleConstant.getOAuthService();
			
			Verifier verifier = new Verifier((String)request.getParameter("oauth_verifier"));
			Token accessToken = service.getAccessToken(requestToken, verifier);		
			
			user.setGMailAccessToken(accessToken.getToken());
			user.setGMailAuthSecrete(accessToken.getSecret());
			UserDAO.getInstance().update(user);
			
			RequestDispatcher rd = request.getRequestDispatcher("/");
			rd.forward(request, response);
			
		} catch (RollbackException e) {
			e.printStackTrace();
		} catch (MyDAOException e) {
			e.printStackTrace();
		}
		
		

		System.out.println("Finish GoogleOAuthCallback");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	
}
